<template>
  <div v-if="show" class="modal-overlay">
    <div class="modal-content">
      <div class="modal-header">
        <h3>初始化库存</h3>
        <button class="close-btn" @click="handleClose">×</button>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <div class="type-selection-container">
            <button 
              class="download-template-btn" 
              @click="downloadTemplate"
              title="下载导入模板"
            >
              <i class="fa fa-download"></i> 下载模板
            </button>
          </div>
        </div>

        <div class="form-group">
          <label for="fileUpload">上传Excel文件</label>
          <div 
            class="file-upload-area"
            :class="{ 
              'error': showError && !selectedFile,
              'has-file': selectedFile
            }"
            @click="triggerFileInput"
            @dragover.prevent="handleDragOver"
            @dragleave.prevent="handleDragLeave"
            @drop.prevent="handleDrop"
          >
            <input 
              type="file" 
              ref="fileInput" 
              @change="handleFileChange" 
              accept=".xlsx,.xls"
              style="display: none;"
            >
            <div v-if="!selectedFile" class="upload-placeholder">
              <i class="fa fa-cloud-upload"></i>
              <p>点击或拖拽文件到此处上传</p>
              <p class="upload-hint">支持 .xlsx, .xls 格式</p>
            </div>
            <div v-else class="file-info">
              <i class="fa fa-file-excel-o"></i>
              <p>{{ selectedFile.name }}</p>
              <button class="remove-file-btn" @click.stop="removeFile">
                <i class="fa fa-times"></i>
              </button>
            </div>
          </div>
          <div class="error-message" v-if="showError && !selectedFile">
            请上传Excel文件
          </div>
        </div>

        <div class="upload-instructions">
          <h4>上传说明：</h4>
          <ul>
            <li>请使用标准Excel模板进行上传</li>
            <li>文件大小不超过10MB</li>
            <li>确保Excel中的数据格式正确</li>
            <li>上传成功后，系统将自动解析并导入数据</li>
          </ul>
        </div>
      </div>
      <div class="modal-footer">
        <button class="cancel-btn" @click="handleClose">取消</button>
        <button 
          class="submit-btn" 
          @click="handleSubmit"
          :disabled="isSubmitting"
        >
          {{ isSubmitting ? '上传中...' : '上传' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { InventoryItemType } from '../../types/inventory';
import { useInventoryStore } from '../../stores/inventoryStore';
import { API_CONFIG } from '../../config/apiConfig';
import { ToastService } from '../../utils/toastService';

// 定义props
const props = defineProps<{
  show: boolean;
  labId: string;
}>();

const emit = defineEmits<{
  (e: 'close'): void;
  (e: 'init-success'): void;
}>();

const selectedType = ref<InventoryItemType>(InventoryItemType.CHEMICAL); // 默认设置为化学试剂(0)
const selectedFile = ref<File | null>(null);
const fileInput = ref<HTMLInputElement | null>(null);
const isSubmitting = ref(false);
const showError = ref(false);
const isDragging = ref(false);

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click();
};

// 处理文件选择
const handleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement;
  if (input.files && input.files.length > 0) {
    selectedFile.value = input.files[0];
  }
};

// 处理拖拽事件
const handleDragOver = (_event: DragEvent) => {
  isDragging.value = true;
};

const handleDragLeave = (_event: DragEvent) => {
  isDragging.value = false;
};

const handleDrop = (event: DragEvent) => {
  isDragging.value = false;
  if (event.dataTransfer?.files && event.dataTransfer.files.length > 0) {
    const file = event.dataTransfer.files[0];
    // 检查文件类型
    if (file.name.endsWith('.xlsx') || file.name.endsWith('.xls')) {
      selectedFile.value = file;
    } else {
      ToastService.error('请上传Excel文件(.xlsx或.xls格式)');
    }
  }
};

// 移除已选择的文件
const removeFile = () => {
  selectedFile.value = null;
  if (fileInput.value) {
    fileInput.value.value = '';
  }
};

// 关闭模态框
const handleClose = () => {
  resetForm();
  emit('close');
};

// 重置表单
const resetForm = () => {
  // selectedType 不再重置，保持默认值 InventoryItemType.CHEMICAL
  selectedFile.value = null;
  if (fileInput.value) {
    fileInput.value.value = '';
  }
  showError.value = false;
};

const inventoryStore = useInventoryStore();

// 下载模板
const downloadTemplate = () => {
  // 构建下载URL，使用默认类型
  const downloadUrl = `${API_CONFIG.BASE_URL}/inventory/init/template/${selectedType.value}/download`;
  
  // 创建一个隐藏的a标签来触发下载
  const link = document.createElement('a');
  link.href = downloadUrl;
  link.target = '_blank';
  
  // 添加凭证，确保cookie被发送
  link.setAttribute('download', '');
  
  // 触发点击
  document.body.appendChild(link);
  link.click();
  
  // 清理DOM
  document.body.removeChild(link);
};

// 提交表单
const handleSubmit = async () => {
  // 显示验证错误
  showError.value = true;
  
  // 验证表单，只检查文件
  if (!selectedFile.value) {
    return;
  }

  isSubmitting.value = true;
  try {
    const formData = new FormData();
    formData.append('file', selectedFile.value);
    // 使用默认类型值 InventoryItemType.CHEMICAL (0)
    formData.append('type', selectedType.value.toString());
    formData.append('researchGroupId', props.labId);

    const result = await inventoryStore.initializeInventory(props.labId, formData);
    
    if (result.success) {
      emit('init-success');
      resetForm();
      emit('close');
    } else {
      ToastService.error(`初始化库存失败: ${result.message || '未知错误'}`);
    }
  } catch (error) {
    console.error('初始化库存请求失败:', error);
    ToastService.error('初始化库存失败，请检查网络连接');
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #999;
  cursor: pointer;
  padding: 4px;
}

.close-btn:hover {
  color: #666;
}

.modal-body {
  padding: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

.form-control {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.type-selection-container {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.type-selection-container .form-control {
  flex: 1;
}

.download-template-btn {
  padding: 8px 12px;
  background-color: #f0f0f0;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  color: #333;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  white-space: nowrap;
  transition: all 0.3s;
}

.download-template-btn:hover:not(:disabled) {
  color: #40a9ff;
  border-color: #40a9ff;
  background-color: #fff;
}

.download-template-btn:disabled {
  background-color: #f5f5f5;
  border-color: #d9d9d9;
  color: #bfbfbf;
  cursor: not-allowed;
}

.download-template-btn i {
  font-size: 14px;
}

.form-control:focus {
  border-color: #40a9ff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.form-control.error {
  border-color: #ff4d4f;
}

.error-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

.file-upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 4px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.file-upload-area:hover {
  border-color: #40a9ff;
}

.file-upload-area.error {
  border-color: #ff4d4f;
}

.file-upload-area.has-file {
  border-color: #52c41a;
  background-color: #f6ffed;
}

.upload-placeholder {
  color: #999;
}

.upload-placeholder i {
  font-size: 32px;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 12px;
  margin-top: 8px;
}

.file-info {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #52c41a;
}

.file-info i {
  font-size: 24px;
  margin-right: 8px;
}

.remove-file-btn {
  background: none;
  border: none;
  color: #ff4d4f;
  cursor: pointer;
  margin-left: 8px;
  padding: 4px;
}

.upload-instructions {
  margin-top: 24px;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.upload-instructions h4 {
  margin-top: 0;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
}

.upload-instructions ul {
  margin: 0;
  padding-left: 20px;
}

.upload-instructions li {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.modal-footer {
  padding: 16px 24px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.cancel-btn,
.submit-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn {
  background: white;
  border: 1px solid #d9d9d9;
  color: #666;
}

.cancel-btn:hover {
  color: #40a9ff;
  border-color: #40a9ff;
}

.submit-btn {
  background: #1890ff;
  border: none;
  color: white;
}

.submit-btn:hover {
  background: #40a9ff;
}

.submit-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}
</style>